<template>
  <BasicModal
    v-bind="$attrs"
    destoryOnClose
    width="45%"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { getDeptTreeByPage, getDeptInfoApi, updateDeptApi, addDeptApi } from '/@/api/admin/dept';
  import { formSchema } from './dept.data';

  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let updateInfo = {};
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (data.record) {
          setFieldsValue({
            parentId: data.record.id,
          });
        }

        if (unref(isUpdate)) {
          const res = await getDeptInfoApi(data.record.id);
          updateInfo = res;
          setFieldsValue({
            ...res,
          });
        }
        const treeData = await getDeptTreeByPage({ deptId: data.record.id });
        const root = [
          {
            id: '0',
            name: '根部门',
            children: treeData,
          },
        ];
        updateSchema([
          {
            field: 'parentId',
            componentProps: { treeData: root },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          const params = Object.assign(updateInfo, values);
          const apiFn = unref(isUpdate) ? updateDeptApi : addDeptApi;
          await apiFn(params);
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
